"""
商品推送记录模型
用于记录已推送的商品，避免重复推送
@deprecated: 此模型已废弃，请使用 NotifyLog 模型替代
"""

from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, Text
from sqlalchemy.types import DECIMAL
from sqlalchemy.dialects.mysql import JSON
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from app.database import Base


class ProductNotification(Base):
    """商品推送记录表"""
    __tablename__ = "product_notifications"

    # 基础字段
    id = Column(Integer, primary_key=True, index=True, comment="推送记录ID")
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="用户ID")
    monitor_id = Column(Integer, ForeignKey("monitors.id"), nullable=False, comment="监控任务ID")
    
    # 商品标识（用于去重）
    product_external_id = Column(String(191), nullable=False, index=True, comment="外部商品ID")  # 适配索引限制
    product_url = Column(Text, nullable=True, comment="商品链接")  # 长URL使用TEXT
    
    # 商品基本信息（用于推送显示）
    product_title = Column(String(500), nullable=False, comment="商品标题")
    product_price = Column(DECIMAL(10, 2), nullable=True, comment="商品价格")
    product_currency = Column(String(10), default="CNY", comment="货币单位")
    seller_name = Column(String(200), nullable=True, comment="卖家名称")
    seller_id = Column(String(100), nullable=True, comment="卖家ID")
    
    # 商品图片和位置
    product_image_url = Column(String(1000), nullable=True, comment="商品主图")
    product_location = Column(String(200), nullable=True, comment="商品所在地")
    
    # 匹配信息
    matched_keyword = Column(String(200), nullable=True, comment="匹配的关键词")
    matched_seller = Column(String(200), nullable=True, comment="匹配的卖家")
    match_type = Column(String(50), nullable=False, comment="匹配类型：keyword/seller")
    
    # 推送状态
    notification_sent = Column(Boolean, default=False, comment="是否已发送通知")
    notification_channel = Column(String(50), nullable=True, comment="通知渠道")
    notification_id = Column(Integer, ForeignKey("notifications.id"), nullable=True, comment="关联通知记录")
    
    # 用户交互
    is_clicked = Column(Boolean, default=False, comment="用户是否点击")
    is_interested = Column(Boolean, nullable=True, comment="用户是否感兴趣")
    user_feedback = Column(String(500), nullable=True, comment="用户反馈")
    
    # 数据来源
    source_platform = Column(String(50), nullable=False, comment="数据来源平台")
    crawl_timestamp = Column(DateTime(timezone=True), nullable=False, comment="爬取时间")
    
    # 时间字段
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关联关系
    user = relationship("User", back_populates="product_notifications")
    monitor = relationship("Monitor", back_populates="product_notifications")
    notification = relationship("Notification", back_populates="product_notification", uselist=False)

    def __repr__(self):
        return f"<ProductNotification(id={self.id}, user_id={self.user_id}, product_id='{self.product_external_id}')>"

    @property
    def cache_key(self):
        """生成Redis缓存键"""
        return f"product_notified:{self.user_id}:{self.product_external_id}"

    @property
    def global_cache_key(self):
        """生成全局缓存键（所有用户共享）"""
        return f"product_seen:{self.product_external_id}"

    def to_dict(self):
        """转换为字典格式"""
        return {
            "id": self.id,
            "product_external_id": self.product_external_id,
            "product_title": self.product_title,
            "product_price": float(self.product_price) if self.product_price else None,
            "product_currency": self.product_currency,
            "seller_name": self.seller_name,
            "product_url": self.product_url,
            "product_image_url": self.product_image_url,
            "product_location": self.product_location,
            "matched_keyword": self.matched_keyword,
            "matched_seller": self.matched_seller,
            "match_type": self.match_type,
            "source_platform": self.source_platform,
            "crawl_timestamp": self.crawl_timestamp.isoformat() if self.crawl_timestamp else None,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "is_clicked": self.is_clicked,
            "is_interested": self.is_interested
        }

    @classmethod
    def create_from_product_data(cls, user_id, monitor_id, product_data, match_info):
        """从商品数据创建推送记录"""
        return cls(
            user_id=user_id,
            monitor_id=monitor_id,
            product_external_id=product_data.get("external_id", ""),
            product_url=product_data.get("product_url", ""),
            product_title=product_data.get("title", ""),
            product_price=product_data.get("price"),
            product_currency=product_data.get("currency", "CNY"),
            seller_name=product_data.get("seller_name", ""),
            seller_id=product_data.get("seller_id", ""),
            product_image_url=product_data.get("main_image_url", ""),
            product_location=product_data.get("location", ""),
            matched_keyword=match_info.get("keyword"),
            matched_seller=match_info.get("seller"),
            match_type=match_info.get("type", "keyword"),
            source_platform=product_data.get("source_platform", ""),
            crawl_timestamp=product_data.get("crawl_timestamp", func.now())
        )
